package com.yzh.search;

/**
 * @author 于振晗
 * @title: TwoSearch
 * @description: TODO 二分查找
 * @date 2020年09月01日
 * @path com.yzh.search
 */
public class TwoSearchTest {
    public static void main(String[] args) {
        int[] arr = getArr();
        int binary = binary(arr, 99999);
        System.out.println(binary);

        int i;
        for (i = 0; i < arr.length; i++) {
            if(arr[i] == 99999){
                break;
            }
        }

        System.out.println("循环查询次数："+i);
    }

    public static int [] getArr(){
        int [] arr = new int[100000];
        for (int i = 0; i < 100000; i++) {
            arr[i] = i+1;
        }
        return arr;
    }


    public static int binary(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        //计数
        int count = 0;
        while (low <= high) {
            count++;
            System.out.println();
            int mid = (low + high) / 2;
            if (arr[mid] > key) {
                high = mid - 1;
            } else if (arr[mid] < key) {
                low = mid + 1;
            } else {
                System.out.println("二分查询次数："+count);
                return mid;
            }
        }
        System.out.println("二分查询次数："+count);
        return -1;
    }
}
